//
// Created by 123 on 2024/12/27.
//
#include "stdio.h"
//定义一个结构体
typedef struct {
    char name[50];
    int age;
    float gpa;
} Student;

int main076(){
    FILE* fp;
    Student s1 = {"zhangsan",18,66};
    Student s2 = {"lisi",20,88};

    //以二进制写入模式打开文件
    fp = fopen("students.bin","wb");
    if(fp == NULL){
        perror("open error");
        return 1;
    }

    //使用filewrite写入结构体数据
    fwrite(&s1,sizeof(Student),1,fp);
    fwrite(&s2,sizeof(Student),1,fp);

    //关闭文件
    fclose(fp);
    printf("binary write over");

    //读取二进制数据
    fp = fopen("students.bin","rb");
    if(fp == NULL){
        perror("open error");
        return 1;
    }

    //使用fread读取数据
    printf("read binary begin...\n");
    Student student;
    int i;
    while (fread(&student,sizeof(Student),1,fp) == 1){
        printf("student:%d\n",++i);
        printf("name:%s\n",student.name);
        printf("age:%d\n",student.age);
        printf("gpa:%.2f\n",student.gpa);
    }
    fclose(fp);

    return 0;
}
